package com.nekonomics
package api.route

import api.dto.request.{UserLoginReq, UserRegisterReq}
import api.dto.response.RspEncoder.*
import api.dto.response.{UserAuthDto, UserProfileDto}
import domain.service.UserService

import zio.*
import zio.http.*
import zio.http.Method.*
import zio.json.*

object UserRoute {

  lazy val routes = baseApiPath / "user" / Routes(
    
    POST / "register" -> handler { (req: Request) =>
      for {
        body <- req.body.asString
        dto <- ZIO.fromEither(body.fromJson[UserRegisterReq])
        userId <- ZIO.serviceWithZIO[UserService](_.register(dto))
        user <- ZIO.serviceWithZIO[UserService](_.queryByUserId(userId))
        rsp = UserProfileDto.fromUserView(user).toRsp.toJson
      } yield Response.json(rsp)
    },

    POST / "login" -> handler { (req: Request) =>
      for {
        body <- req.body.asString
        dto <- ZIO.fromEither(body.fromJson[UserLoginReq])
        res <- ZIO.serviceWithZIO[UserService](_.login(dto))
        rsp = UserAuthDto.fromAuthRes(res).toRsp.toJson
      } yield Response.json(rsp)

    },
    GET / "me" -> handler { (req: Request) =>
      for {
        jwt  <-  extractJwt(req)
        userView <- ZIO.serviceWithZIO[UserService](_.verifyToken(jwt))
        rsp = UserProfileDto.fromUserView(userView).toRsp.toJson
      } yield Response.json(rsp)

    }


  )

}
